package cn.unknowpupil.init.controller.common;

import cn.unknowpupil.init.common.constant.CommonConstants;
import cn.unknowpupil.init.common.constant.SecurityConstants;
import cn.unknowpupil.init.common.enums.BusinessType;
import cn.unknowpupil.init.common.resopnse.ResultResponse;
import cn.unknowpupil.init.components.annotation.Limit;
import cn.unknowpupil.init.components.annotation.Log;
import cn.unknowpupil.init.components.annotation.rest.AnonymousGetMapping;
import cn.unknowpupil.init.components.annotation.rest.AnonymousPostMapping;
import cn.unknowpupil.init.domain.dto.LoginUser;
import cn.unknowpupil.init.service.system.ICommonService;
import cn.unknowpupil.init.utils.file.FileUtils;
import cn.unknowpupil.init.utils.security.SecurityUtils;
import cn.unknowpupil.init.utils.strings.StringUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;

/**
 * Created at 2020/11/2 by w10g <br>
 * Initialize CommonController ... <br>
 *
 * @author unknowpupil
 * @since 0.0.1
 */
@Api(tags = {"系统-公共模块"}, value = "Common")
@RestController
@RequestMapping("common")
@Slf4j
public class CommonController {
    @Autowired
    private ICommonService commonService;


    @ApiOperation("公共：下载")
    @AnonymousGetMapping("download")
    public void remove(String fileName, Boolean delete, HttpServletResponse response, HttpServletRequest request) {
        try {
            if (!FileUtils.isValidFilename(fileName)) {
                throw new Exception(StringUtils.format("文件名称({})非法，不允许下载。 ", fileName));
            }
            String realFileName = System.currentTimeMillis() + fileName.substring(fileName.indexOf("_") + 1);
            String filePath = CommonConstants.DOWNLOAD_PATH + fileName;

            response.setCharacterEncoding("utf-8");
            response.setContentType("multipart/form-data");
            response.setHeader("Content-Disposition",
                    "attachment;fileName=" + FileUtils.setFileDownloadHeader(request, realFileName));
            FileUtils.writeBytes(filePath, response.getOutputStream());
            if (delete) {
                FileUtils.deleteFile(filePath);
            }
        } catch (Exception e) {
            log.error("下载文件失败", e);
        }
    }

    @AnonymousPostMapping("upload")
    @ApiOperation("上传文件")
    public ResultResponse upload(@RequestParam("file") MultipartFile file) throws IOException {
        String path = commonService.uploadFile(file);
        return ResultResponse.buildSuccess(path);

    }

    @ApiOperation("公共：下载 信息")
    @GetMapping("file/download")
    public void netDownLoadNet(String netAddress,String fileName,HttpServletResponse response,HttpServletRequest request) throws Exception {
        URL url = new URL(netAddress);
        URLConnection conn = url.openConnection();
        InputStream inputStream = conn.getInputStream();
        response.reset();
        response.setContentType(conn.getContentType());
        response.setHeader("Access-Control-Allow-Origin", "*"); // 允许所有
        // response.setHeader("Access-Control-Allow-Origin", "http://127.0.0.1, http://locahost"); // 允许白名单IP
        // 响应类型
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
        // 预检请求的结果缓存60分钟
        response.setHeader("Access-Control-Max-Age", "3600");
        // 响应头设置
        //response.setHeader("Access-Control-Allow-Headers", "x-requested-with");
        response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName, "UTF-8"));
        response.addHeader("Content-Length",""+conn.getContentLength());
        response.setContentType("application/octet-stream");
        response.setContentType("application/json;charset=utf-8");
        System.out.println("size:"+conn.getContentLength());
        byte[] buffer = new byte[409600];
        int len;
        OutputStream outputStream = response.getOutputStream();
        while ((len = inputStream.read(buffer)) > 0) {
            outputStream.write(buffer, 0, len);
        }
        inputStream.close();
    }
    @ApiOperation("系统：限流测试管理 权限")
    @Limit(key = "test", period = 60, count = 10, name = "testLimit", prefix = "limit")
    @PreAuthorize("hasRole('ROLE_USER')")
    @GetMapping("test")
    public ResultResponse test() {
        return ResultResponse.buildSuccess(1);
    }

}
